<template>
  <div>
    <el-button type="primary" @click="openAddDialog">添加客房</el-button>
    <el-input v-model="hotelId" placeholder="请输入酒店ID" style="width: 200px; margin-left: 20px;"></el-input>
    <el-button type="primary" @click="searchRooms">搜索</el-button>

    <el-table :data="paginatedRooms" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="ID" width="50"></el-table-column>
      <el-table-column prop="roomNum" label="客房号" width="100"></el-table-column>
      <el-table-column prop="roomType" label="客房类型" width="100"></el-table-column>
      <el-table-column prop="rztime" label="入住时间" width="180"></el-table-column>
      <el-table-column prop="tftime" label="退房时间" width="180"></el-table-column>
      <el-table-column prop="breakFast" label="早餐类型" width="100"></el-table-column>
      <el-table-column prop="price" label="价格" width="100"></el-table-column>
      <el-table-column prop="hotelId" label="酒店ID" width="80"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteRoom(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
        style="margin-top: 20px;"
        background
        layout="prev, pager, next"
        :total="totalRooms"
        :page-size="pageSize"
        @current-change="handlePageChange"
    ></el-pagination>

    <!-- 编辑客房对话框 -->
    <el-dialog title="编辑客房" v-model="isEditDialogVisible">
      <el-form :model="editForm">
        <el-form-item label="客房号">
          <el-input v-model="editForm.roomNum"></el-input>
        </el-form-item>
        <el-form-item label="客房类型">
          <el-input v-model="editForm.roomType"></el-input>
        </el-form-item>
        <el-form-item label="入住时间">
          <el-date-picker v-model="editForm.rztime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="退房时间">
          <el-date-picker v-model="editForm.tftime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="早餐类型">
          <el-input v-model="editForm.breakFast"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="editForm.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="酒店ID">
          <el-input v-model="editForm.hotelId"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateRoom">确认</el-button>
      </div>
    </el-dialog>

    <!-- 添加客房对话框 -->
    <el-dialog title="添加客房" v-model="isAddDialogVisible">
      <el-form :model="addForm">
        <el-form-item label="客房号">
          <el-input v-model="addForm.roomNum"></el-input>
        </el-form-item>
        <el-form-item label="客房类型">
          <el-input v-model="addForm.roomType"></el-input>
        </el-form-item>
        <el-form-item label="入住时间">
          <el-date-picker v-model="addForm.rztime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="退房时间">
          <el-date-picker v-model="addForm.tftime" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="早餐类型">
          <el-input v-model="addForm.breakFast"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="addForm.price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="酒店ID">
          <el-input v-model="addForm.hotelId"></el-input>
        </el-form-item>
      </el-form>
      <!-- eslint-disable-next-line -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRoom">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import { listRooms, deleteRoom as deleteRoomAPI, updateRoom as updateRoomAPI, addRoom as addRoomAPI, getRoomsByHotelId } from '@/api/room.js';
import { ElMessageBox, ElMessage } from 'element-plus';
import moment from 'moment';

const rooms = ref([]);
const paginatedRooms = ref([]);
const currentPage = ref(1);
const pageSize = 15;
const totalRooms = ref(0);
const isEditDialogVisible = ref(false);
const isAddDialogVisible = ref(false);
const hotelId = ref('');
const editForm = ref({
  id: '',
  roomNum: '',
  roomType: '',
  rztime: '',
  tftime: '',
  breakFast: '',
  price: '',
  hotelId: ''
});

const addForm = ref({
  roomNum: '',
  roomType: '',
  rztime: '',
  tftime: '',
  breakFast: '',
  price: '',
  hotelId: ''
});

const fetchRooms = async () => {
  try {
    const response = await listRooms();
    if (response.code === 1) {
      rooms.value = response.data;
      totalRooms.value = rooms.value.length;
      paginateRooms();
    } else {
      throw new Error(response.msg);
    }
  } catch (error) {
    console.error('Error fetching rooms:', error);
  }
};

const searchRooms = async () => {
  if (!Number.isInteger(parseInt(hotelId.value))) {
    ElMessage({
      type: 'error',
      message: '请输入有效的酒店ID（整数）'
    });
    return;
  }

  try {
    const response = await getRoomsByHotelId(parseInt(hotelId.value));
    if (response.code === 1) {
      rooms.value = response.data;
      totalRooms.value = rooms.value.length;
      paginateRooms();
    } else {
      throw new Error(response.msg);
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '获取客房列表失败'
    });
    console.error('Error searching rooms:', error);
  }
};

const paginateRooms = () => {
  const start = (currentPage.value - 1) * pageSize;
  const end = start + pageSize;
  paginatedRooms.value = rooms.value.slice(start, end);
};

const handlePageChange = (page) => {
  currentPage.value = page;
  paginateRooms();
};

const openEditDialog = (room) => {
  editForm.value = { ...room };
  isEditDialogVisible.value = true;
};

const openAddDialog = () => {
  addForm.value = {
    roomNum: '',
    roomType: '',
    rztime: '',
    tftime: '',
    breakFast: '',
    price: '',
    hotelId: ''
  };
  isAddDialogVisible.value = true;
};

const formatDateTime = (dateTime) => {
  return moment(dateTime).format('YYYY-MM-DD HH:mm:ss');
};

const updateRoom = async () => {
  try {
    const updatedRoom = {
      ...editForm.value,
      rztime: formatDateTime(editForm.value.rztime),
      tftime: formatDateTime(editForm.value.tftime)
    };
    await updateRoomAPI(updatedRoom);
    ElMessage({
      type: 'success',
      message: '更新客房成功!'
    });
    isEditDialogVisible.value = false;
    fetchRooms();
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '更新客房失败'
    });
    console.error('Error updating room:', error);
  }
};

const addRoom = async () => {
  try {
    const newRoom = {
      ...addForm.value,
      rztime: formatDateTime(addForm.value.rztime),
      tftime: formatDateTime(addForm.value.tftime)
    };
    await addRoomAPI(newRoom);
    ElMessage({
      type: 'success',
      message: '添加客房成功!'
    });
    isAddDialogVisible.value = false;
    fetchRooms();
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '添加客房失败'
    });
    console.error('Error adding room:', error);
  }
};

const deleteRoom = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该客房吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteRoomAPI(id);
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
    fetchRooms();
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除客房失败'
    });
    console.error('Error deleting room:', error);
  }
};

onMounted(() => {
  fetchRooms();
});
</script>

<style scoped>
/* 添加你的样式 */
</style>
